package cn.loioi.websocket.pool;

import org.apache.commons.pool2.SwallowedExceptionListener;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :连接池 <br>
 * @file_name :ConnecttionPool.java <br>
 * @system_name :bs-iot <br>
 * @author :yyzh <br>
 * @创建时间 :2016年7月11日 下午5:04:04
 */
@Component
public class ConnecttionPool extends GenericKeyedObjectPool<String, Connecttion> {
	private Logger logger = LoggerFactory.getLogger(ConnecttionPool.class);

	public ConnecttionPool() {
		super(new ConnecttionPoolFactory(), getConfig());
		logger.debug("连接池启动...");
		this.setSwallowedExceptionListener(new SwallowedExceptionListener() {
			@Override
			public void onSwallowException(Exception e) {
				logger.debug("连接异常", e);
			}
		});
	}

	@Override
	public void addObject(String account) throws Exception {
		logger.debug("连接入栈:" + account);
		super.addObject(account);
	}

	@Override
	public void clear(String account) {
		super.clear(account);
		logger.debug("连接出栈:" + account);
	}

	public void returnObject(Connecttion obj) {
		if (obj == null) { throw new IllegalStateException(); }
		super.returnObject(obj.getAccount(), obj);
	}

	private static GenericKeyedObjectPoolConfig getConfig() {
		GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
		config.setMaxTotal(500);// 整个池最大值
		config.setMaxTotalPerKey(1);// 每个key的最大
		config.setMaxWaitMillis(500L);// 阻塞等待最大时长
		config.setEvictionPolicyClassName(EvictionPolicy.class.getName());
		config.setTestWhileIdle(false);
		config.setMinEvictableIdleTimeMillis(3 * 60 * 1000L);// 连接最大空闲时间
		return config;
	}
}
